package com.ruoyi.common.utils.agent;

import com.ruoyi.common.utils.http.RestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;
import java.util.Map;


/**
 * 执行请求jwagent Rest，获取请求结果
 */

public class AgentRestUtil {

    private static final Logger log = LoggerFactory.getLogger(AgentRestUtil.class);
    public static String GET_HOST_METRIC_URL="http://ip:port/metrics/node/host";
    public static String POST_EXEC_COMMAND_URL="http://ip:port/api/v1/exec";
    public static String POST_UPLOAD_FILE_URL="http://ip:port/api/v1/upload";
    public static String GET_UPLOAD_FILE_EXIST="http://ip:port/api/v1/check-upload-file-exists";
    public static String POST_DECOMPRESS_RPM="cd install_dir && rpm2cpio rmp_filepath | cpio -di " +
            "&& mv home/admin/kingwow/* . && rm -r home " +
            "&& mkdir -p tools && cp bin/{mg_admin,tg_admin,dg_admin,import_v2,export_v2} tools/";
    public static String POST_GET_DIR_DISK="df -B 1g data_path |tail -n 1|awk '{print $4}'";
    public static String POST_MK_DIR_DISK="mkdir -p {dirlist}";
    public static String POST_REBULID_DIR="cd scripts_dir && bash RebuildDir.sh";

    public static final String COMMAND_CHECK_PORT_USED = "netstat -tln | grep :";
    public static final String COMMAND_CHECK_DIR_EXIST = "test -d dir && test -r dir && test -w dir && test -x dir";
    public static final String COMMAND_CHECK_DIR_EMPTY = "test -z \"$(ls -A dir)\"";
    public static final String COMMAND_START_DB_NODE = "cd ~/kw_root_dir && LD_LIBRARY_PATH=/usr/local/lib64/:lib:$LD_LIBRARY_PATH start_cmd";
    public static final String COMMAND_KILL_DB_NODE = "cat ~/kw_root_dir/run/node_type.pid|xargs --no-run-if-empty kill -9";
    public static final String COMMAND_CHECK_NODE_PROCESS = "ps -ef|grep bin/node_bin|grep node_port|awk '{print $2}'";
    public static final String COMMAND_BOOTSTRAP_CLUSTER = "cd ~/kw_root_dir/tools && ./mg_admin -r master_ip -p master_port -t 600000000 boot_strap";
    public static final String COMMAND_RM_RF_DATA_DIR = "rm -rf {data_dir,}";

    public static String sendGet(String url,String username,String passwd){
        RestTemplate template = RestUtils.getRestTemplate(username,passwd);
        String result = template.getForObject(url,String.class);
        return result;
    }

    public static String getHostMetrics(String ip,String port,String username,String passwd){
        String url = GET_HOST_METRIC_URL.replaceAll("ip",ip).replace("port",port);
        log.debug(url+","+username+":"+passwd);
        return sendGet(url,username,passwd);
    }

    public static AgentResult getHostFileExist(AgentRequest request){
        String url = GET_UPLOAD_FILE_EXIST.replaceAll("ip",request.getIp()).replace("port",request.getPort());
        RestTemplate template = RestUtils.getRestTemplate(request.getUsername(),request.getPassword());
        url +="?filename="+request.getCommand();
        AgentResult  result = template.getForObject(url,AgentResult.class);
        return result;
    }

    public static AgentResult postAgentCommand(AgentRequest request){
        String url = POST_EXEC_COMMAND_URL.replaceAll("ip",request.getIp()).replace("port",request.getPort());
        RestTemplate template = RestUtils.getRestTemplate(request.getUsername(),request.getPassword());
        Map param = new HashMap<>();
        param.put("command",request.getCommand());
        AgentResult  result = template.postForObject(url,param,AgentResult.class);
        return result;
    }

    public static AgentResult postAgentUpload(AgentRequest request){
        String url = POST_UPLOAD_FILE_URL.replaceAll("ip",request.getIp()).replace("port",request.getPort());
        RestTemplate template = RestUtils.getRestTemplate(request.getUsername(),request.getPassword());
        // 设置请求参数
        MultiValueMap<String, Object> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("uploadfilename", new FileSystemResource(request.getCommand()));
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 创建HttpEntity对象
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        AgentResult  result = template.postForObject(url,requestEntity,AgentResult.class);
        return result;
    }



}
